package fm.dongman.animefm.view.fragment

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v4.view.ViewPager
import android.support.v4.widget.NestedScrollView
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.*
import fm.dongman.animefm.R
import fm.dongman.animefm.contractlib.IModel
import fm.dongman.animefm.contractlib.contract.HomeContract
import fm.dongman.animefm.view.activity.SettingActivity
import fm.dongman.animefm.view.activity.SingleActivity
import fm.dongman.animefm.view.adapter.*
import fm.dongman.animefm.view.util.ActivityHelper
import fm.dongman.animefm.view.util.BannerHelper
import fm.dongman.animefm.view.util.SystemHelper
import fm.dongman.animefm.view.util.ToastHelper
import fm.dongman.animefm.view.widget.MultiStateLayout
import fm.dongman.modellib.StaticArea.Injection
import fm.dongman.modellib.model.BannerModel
import fm.dongman.presenterlib.presenter.HomePresenter
import fm.dongman.presenterlib.util.NetworkHelper
import kotlinx.android.synthetic.main.fragment_home.*
import kotlinx.android.synthetic.main.layout_home.*
import org.jetbrains.anko.backgroundColor
import org.jetbrains.anko.backgroundResource
import org.jetbrains.anko.onClick
import org.jetbrains.anko.startActivity


/**
 * 首页碎片
 * Created by shize on 2017/9/28.
 */
open class HomeFragment : BaseFragment(), HomeContract.IHomeView {
    private lateinit var mPresenter: HomeContract.IHomePresenter // 全局数据控制器

    private val mCommentList: ArrayList<IModel.ICommentModel> = ArrayList() //最新评论
    private lateinit var mCommentListAdapter: HomeCommentAdapter         //最新评论适配器

    private val mArticleList: ArrayList<IModel.IArticleModel> = ArrayList() //最新文章
    private lateinit var mArticleAdapterListAdapter: HomeArticleAdapter        //最新文章适配器

    private val mSheetList: ArrayList<IModel.ISheetModel> = ArrayList() // 漫单推荐
    private lateinit var mSheetListAdapter: HomeSheetAdapter        // 漫单推荐适配器

    private val mComicList: ArrayList<IModel.IComicModel> = ArrayList() // 人气番剧
    private lateinit var mComicListAdapter: HomeHotComicAdapter        // 人气番剧适配器

    private val mFMList: ArrayList<IModel.IComicModel> = ArrayList() // 独家推荐
    private lateinit var mFMListAdapter: HomeAnimeRecommendAdapter        // 独家推荐适配器


    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
        val fragment = inflater?.inflate(R.layout.fragment_home, container, false)
        // 初始化控制器
        HomePresenter(this, Injection.provideHomeRepository(container!!.context))
        return fragment!!
    }

    override fun setPresenter(presenter: HomeContract.IHomePresenter) {
        mPresenter = presenter
    }

    /**
     * 初始化数据
     */
    override fun initData() {
        loadingContent()
        initTitleBar()
    }

    //是否显示toolbar的颜色
    private var mIsShowTitleBarColor = false

    private fun initTitleBar() {
        mHomeNestedScrollView.setOnScrollChangeListener { v: NestedScrollView?, scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int ->
            if (scrollY > mRlHomeBanner.height / 3 && !mIsShowTitleBarColor) {
                mIsShowTitleBarColor = true
                mTbHome.backgroundResource = R.color.primary
            } else if (scrollY < mRlHomeBanner.height / 3 && mIsShowTitleBarColor) {
                mIsShowTitleBarColor = false
                mTbHome.backgroundResource = android.R.color.transparent
            }
        }
    }

    /**
     * 绑定数据
     */
    override fun bindData() {
        bindToolbar()
        bindSwipe()
        bindBtnClick()
        bindAdapter()
    }

    /**
     * 绑定适配器
     */
    private fun bindAdapter() {
        // 评论列表初始化
        mCommentListAdapter = HomeCommentAdapter(mCommentList, activity)   //全局adapter变量初始化赋值
        mRvNewComments.adapter = mCommentListAdapter                        //全局列表赋值
        mRvNewComments.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)   //初始化布局
        // 文章初始化
        mArticleAdapterListAdapter = HomeArticleAdapter(mArticleList, activity)
        mRvTheLatestArticle.adapter = mArticleAdapterListAdapter
        mRvTheLatestArticle.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
        // 漫单推荐初始化
        mSheetListAdapter = HomeSheetAdapter(mSheetList, activity)
        mRvSheet.adapter = mSheetListAdapter
        mRvSheet.layoutManager = GridLayoutManager(activity, 2, GridLayoutManager.VERTICAL, false)
        // 人气番剧初始化
        mComicListAdapter = HomeHotComicAdapter(mComicList, activity)
        mRvHotAnime.adapter = mComicListAdapter
        mRvHotAnime.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
        // 独家推荐初始化
        mFMListAdapter = HomeAnimeRecommendAdapter(mFMList, activity)
        mRvComicRecommend.adapter = mFMListAdapter
        mRvComicRecommend.layoutManager = LinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false)
    }


    override fun showHomeBanners(banners: List<IModel.IBannerModel>) {
        loadedContent()
        val imageList = ArrayList<String>()
        banners.forEach {
            imageList.add((it as BannerModel).imgUrl)
        }

        BannerHelper.getBannerImages(mHomeBanner, imageList)
        mHomeBanner.setOnItemClickListener { position ->
            // 横幅点击事件
            val banner = banners[position] as BannerModel
            if (banner.subjectId.isNotEmpty())
                ActivityHelper.startActivity(activity, SingleActivity::class.java, mapOf(
                        Pair(SingleActivity.EXTRA_NAME, SingleActivity.INTENT_EXTRA_ANIME_INFO),
                        Pair(SingleActivity.BUNDLE_EXTRA_KEY_ID, banner.subjectId)),
                        false)
        }
        bindBannerTitle(banners)
    }

    /**
     * 绑定轮播图标题
     */
    @SuppressLint("SetTextI18n")
    private fun bindBannerTitle(banners: List<IModel.IBannerModel>) {
        // title 初始值
        if (banners.isEmpty()) return
        mHomeBannerTitle.text = (banners[0] as BannerModel).title
        mHomeBannerCurNum.text = "1/${banners.size}"

        mHomeBanner.onPageChangeListener = object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {}
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}
            override fun onPageSelected(position: Int) {
                mHomeBannerTitle.text = (banners[position] as BannerModel).title
                mHomeBannerCurNum.text = "${position + 1}/${banners.size}"
            }
        }
    }

    //独家推荐
    override fun showHomeFMRecommendList(fmList: List<IModel.IComicModel>) {
        mFMList.clear()
        mFMList.addAll(fmList)
        mFMListAdapter.notifyDataSetChanged()
    }

    //人气番剧热门周榜
    override fun showHotRankComicList(comicList: List<IModel.IComicModel>) {
        mComicList.clear()
        if (comicList.size > 5)
            mComicList.addAll(comicList.subList(0, 5))
        else
            mComicList.addAll(comicList)
        mComicListAdapter.notifyDataSetChanged()
    }

    //漫单推荐
    override fun showHomeSheetRecommendList(sheetList: List<IModel.ISheetModel>) {
        mSheetList.clear()
        if (sheetList.size > 6)
            mSheetList.addAll(sheetList.subList(0, 6))
        else
            mSheetList.addAll(sheetList)
        mSheetListAdapter.notifyDataSetChanged()
    }

    //最新文章
    override fun showHomeNewArticleList(articleList: List<IModel.IArticleModel>) {
        mArticleList.clear()
        if (articleList.size > 6)
            mArticleList.addAll(articleList.subList(0, 6))
        else
            mArticleList.addAll(articleList)
        mArticleAdapterListAdapter.notifyDataSetChanged()
    }

    //漫单评论
    override fun showHomeNewCommentList(commentList: List<IModel.ICommentModel>) {
        mCommentList.clear()
        mCommentList.addAll(commentList) //赋值
        mCommentListAdapter.notifyDataSetChanged() //通知更新

    }

    override fun showNoNetwork() {
        mHomeSwipeRefreshLayout?.isRefreshing = false
        mHomeMultiStateLayout?.changeState(MultiStateLayout.NET_ERROR)
    }

    override fun showRefreshFailed() {
        mHomeSwipeRefreshLayout?.isRefreshing = false
        if (NetworkHelper.isNetworkAvailable(activity)) {
            ToastHelper.getInstance(activity).showError("数据加载失败")
            return
        }
        ToastHelper.getInstance(activity).showError("没有连接网络")
    }

    override fun isActive(): Boolean = isAdded

    override fun getViewContext(): Context = activity

    override fun onStart() {
        super.onStart()
        mPresenter.startLoad()
    }

    private fun bindBtnClick() {
        // 更多漫单推荐事件
        mBtnSheetMore.onClick {
            ActivityHelper.startActivity(activity, SingleActivity::class.java, mapOf(
                    Pair(SingleActivity.EXTRA_NAME, SingleActivity.INTENT_EXTRA_SHEET_LIST),
                    Pair(SingleActivity.BUNDLE_EXTRA_KEY_TYPE, SheetListFragment.TYPE_MANDAN)),
                    false)
        }

        // 更多人气番剧事件
        mBtnRvhot.onClick {
            ActivityHelper.startActivity(activity, SingleActivity::class.java, mapOf(
                    Pair(SingleActivity.EXTRA_NAME, SingleActivity.INTENT_EXTRA_RANK_INFO),
                    Pair(SingleActivity.BUNDLE_EXTRA_KEY_ID, RankInfoFragment.FIND_INFO_WEEK_HOT)),
                    false)
        }
        // 加载更多最新评论
        mBtnCommentsMore.onClick {
            if (!mCommentListAdapter.loadMore()) {
                mBtnCommentsMore.visibility = View.GONE
            }
        }
    }

    /**
     * 绑定 Toolbar
     */
    private fun bindToolbar() {
        mTbHome.setPadding(0, SystemHelper.getStatusBarHeight(activity), 0, 0)
        mTbHome.inflateMenu(R.menu.menu_home_toolbar)

        //主页搜索按钮事件
        mHomeSearch.setOnClickListener {
            val intent = Intent(activity, SingleActivity::class.java)
            intent.putExtra(SingleActivity.EXTRA_NAME, SingleActivity.INTENT_EXTRA_SEARCH)
            ActivityHelper.startActivity(activity, intent)
        }
        //主页菜单项单击事件
        mTbHome.setOnMenuItemClickListener { item ->
            when (item.itemId) {
                R.id.item1 -> {
                    activity.startActivity<SettingActivity>()
                }
            }
            return@setOnMenuItemClickListener true
        }
    }

    /**
     * 绑定下拉刷新
     */
    private fun bindSwipe() {
        mHomeSwipeRefreshLayout.setColorSchemeResources(R.color.primary)
        mHomeSwipeRefreshLayout.setOnRefreshListener {
            mPresenter.refreshPage()
        }
    }

    /**
     * 加载完成后
     */
    private fun loadedContent() {
        mHomeSwipeRefreshLayout?.isRefreshing = false
        mHomeMultiStateLayout?.changeState(MultiStateLayout.SUCCESS)
    }

    /**
     * 加载中
     */
    private fun loadingContent() = mHomeMultiStateLayout?.changeState(MultiStateLayout.LOADING)


    override fun onResume() {
        super.onResume()
        mHomeBanner.startTurning(4000)
    }

    override fun onPause() {
        super.onPause()
        mHomeBanner.stopTurning()
    }

    companion object {
        private var FRAGMENT_INSTANCE: HomeFragment? = null

        /**
         * 获取实例
         */
        fun getInstance(): HomeFragment {
            if (FRAGMENT_INSTANCE == null) {
                FRAGMENT_INSTANCE = HomeFragment()
            }
            return FRAGMENT_INSTANCE!!
        }

        /**
         * 销毁实例
         */
        fun destroyInstance() {
            FRAGMENT_INSTANCE = null
        }
    }
}